package com.backup.information;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 获取到json类型的字符串文件
 * @author 司啸飞
 * @create 2021-05-16 18:38
 */
public class MyGetJson {
    private String mid;
    private JSONObject jsonObject;

    public JSONObject getJsonObject() {
        return jsonObject;
    }

    /**
     * 有参构造
     */
    public MyGetJson(String mid) throws Exception {
        this.mid = mid;
        jsonObject = new JSONObject();
        addCode(MyConstant.getFollowerAPIUrl(mid));
        addCode(MyConstant.getNameAPIUrl(mid));
        GetImage.getPortrait(mid);
    }

    public MyGetJson() {
    }

    /**
     * 使用IO流获取到json的源码
     * @param myUrl
     * @return code
     * @throws Exception
     */
    private String getJsonCode(String myUrl) throws Exception {
        URL url = new URL(myUrl);
        HttpURLConnection httpUrl = (HttpURLConnection)url.openConnection();
        InputStream is = httpUrl.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    /**
     * 将粉丝数、关注数、UID添加进JSONObject对象
     * @throws Exception
     */
    public void addCode(String myUrl) throws Exception {
        String code = getJsonCode(myUrl);
        JSONObject jo = JSONObject.parseObject(code);
        String data = jo.getString("data");
        jo = JSONObject.parseObject(data);
        jsonObject.putAll(jo);
    }


}
